﻿/* 
 * Since 2008 - 2012
 */
package com.hh.bss.auth.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;
import static com.hh.bss.util.extjs.JsonHelper.outJsonArray;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.filters.MappingPropertyFilter;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.google.code.kaptcha.Constants;
import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.dao.*;
import com.hh.bss.auth.entity.*;
import com.hh.bss.auth.service.*;
import com.hh.bss.auth.vo.query.*;
import com.hh.bss.base.*;
import com.hh.bss.common.cache.SystemRoleResourceCache;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.common.exception.SystemException;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.project.entity.ContractJobCvCrm;
import com.hh.bss.project.vo.query.ContractJobCvCrmQuery;
import com.hh.bss.sysadmin.entity.SystemDic;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;




@Controller
public class SystemUserController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private SystemUserService systemUserService;

	private SystemUser systemUser;
	java.lang.Integer id = null;
	private String[] items;

	/** 通过spring自动注入 */
	public void setSystemUserServiceImpl(SystemUserService service) {
		this.systemUserService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	
	
	public void get(HttpServletRequest request, HttpServletResponse response, SystemUser systemUser) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			SystemUser oldSystemUser = (SystemUser) systemUserService.getById(systemUser.getId());

			if (oldSystemUser != null)
				result.put("data", oldSystemUser);
			result.put("success", true);
			result.put("msg", "成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void urlauth(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 检查是否有权限
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			String url = request.getParameter("url");
			String urlName = SystemRoleResourceCache.getSystemResourceNameURL(url);
			boolean isauth = SystemUserCache.isUerAuth(onlineManager.getOnlineUser().getId(), url);
			if (!isauth)
				throw new Exception("对不起，您没有\"" + urlName + "\"操作权限!");
			result.put("success", true);
			result.put("msg", "成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void userresourcelist(HttpServletRequest request, HttpServletResponse response) throws IOException {
		com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
		Integer userId = onlineManager.getOnlineUser().getId();
		Map m = SystemUserCache.getUserResources(userId);
		Map allResource = SystemRoleResourceCache.getAllSystemResource();

		Map resourceMap = new HashMap();

		for (Iterator it = allResource.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			SystemResource r = (SystemResource) allResource.get(key);
			Map data = new HashMap();
			data.put("url", key);
			data.put("name", r.getName());
			data.put("auth", new Integer(0));
			if (SystemUserCache.isUerAuth(userId, key))
				data.put("auth", new Integer(1));
			resourceMap.put(r.getEntryUrl(), data);
		}

		StringBuffer sb = new StringBuffer();

		sb.append("var allResource=").append(JSONObject.fromObject(resourceMap).toString()).append(";");

		JsonHelper.outJsonString(response, sb.toString());
		// outJson(response,resourceMap);
	}

	public ModelAndView userlogout(HttpServletRequest request, HttpServletResponse response) {
		OnlineManager onlineManager = new OnlineManager(request, response);
		onlineManager.signOut();
		ModelAndView mav = new ModelAndView("redirect:/");
		return mav;

	}

	public void userlogin(HttpServletRequest request, HttpServletResponse response) {
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		// view.setContentType("text/html");
		view.setContentType("application/json");
		String inputCode = request.getParameter("randomCode");
		String realCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String realVerifyCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		String verifyCode = request.getParameter("verifyCode"); //验证码
		String save_login = request.getParameter("save_login");
		String ip = request.getRemoteAddr(); // 客户端IP
		String pageURI = request.getRequestURI().replaceFirst(request.getContextPath(), "");
		ModelAndView mav = null;
		Map<String, Object> result = new HashMap<String, Object>();

		
		if(StringUtils.isEmpty(verifyCode)){
	    	result.put("success", false);
			result.put("msg", "登录失败,请输入验证码.");
			outJson(response, result);
			return;
	    }
	    if(!verifyCode.equals(realVerifyCode)){
	    	result.put("success", false);
			result.put("msg", "登录失败,验证码错误.");
			outJson(response, result);
			return;
	    }
		
		
		// 参数错用户名或密码为空
		if (StringHelper.isEmpty(password) || StringHelper.isEmpty(username)) {

			result.put("success", false);
			result.put("msg", "登录失败，请确认是否输入正确的用户名和密码");
			outJson(response, result);
			return;

		}

		SystemUser systemUser = systemUserService.findByUsername(username);
		// 用户不存在或密码错误
		String md5passwd = MD5Helper.encode(password + Environment.PASSWORD_MD5_KEY);
		if (systemUser == null || !md5passwd.equals(systemUser.getPasswd())) {
			result.put("success", false);
			result.put("msg", "登录失败，请确认是否输入正确的用户名和密码");
			outJson(response, result);
			return;
		}

		if (!SystemUser.USER_STATUS_NORMAL.equals(systemUser.getStatus())) {
			result.put("success", false);
			result.put("msg", "当前用户已被锁定,请联系管理员解锁");
			outJson(response, result);
			return;
		}
		// 设置cookie

		OnlineManager onlineManager = new OnlineManager(request, response);
		OnlineUser onlineUser = new OnlineUser();
		onlineUser.setId(systemUser.getId());
		onlineUser.setUsername(systemUser.getAccount());
		onlineUser.setType(0);
		onlineUser.setHistoryId(systemUser.getId());
		onlineUser.setSignInTime(new Date());
		onlineUser.setName(systemUser.getName());
		Map m = SystemUserCache.getUserRoles(systemUser.getId());
		// m.keySet()
		if (m != null) {
			StringBuffer sb = new StringBuffer();
			for (Iterator it = m.keySet().iterator(); it.hasNext();) {
				if (sb.length() > 0)
					sb.append(",").append(it.next());
				else
					sb.append(it.next());
			}
			onlineUser.setRoleIds(sb.toString());
		}
		onlineManager.signIn(onlineUser);

		try {
			onlineManager.addCookie("name", URLEncoder.encode(systemUser.getName(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		onlineManager.addCookie("username", systemUser.getAccount());
		onlineManager.addCookie("id", systemUser.getId().toString());
		if (StringUtils.isNotEmpty(save_login) && "1".equals(save_login)) {
			onlineManager.addCookie("password", password);
			logger.info("U/P:" + username + "=" + password);
		} else {
			onlineManager.removeCookie("password");
		}

		System.out.println(onlineUser.getRoleIds());
		if (!StringHelper.isEmpty(onlineUser.getRoleIds()))
			onlineManager.addCookie("role", onlineUser.getRoleIds());
		if(systemUser.getBranchCompanyId() !=null){
			onlineManager.addCookie("branchCompanyId", systemUser.getBranchCompanyId().toString());
		}
		// 验证Ip 和权限
		if (!this.systemUserService.validateIP(ip)) {
									
			if (!onlineManager.hasPermission(pageURI,onlineUser)) {
				result.put("success", false);
				result.put("msg", "登录失败,由于您不是在办公室登陆,IP受限,请联系管理员取得相应的授权.");
				outJson(response, result);
				return;
			}

		}
		result.put("success", true);
		result.put("msg", "成功!");
		outJson(response, result);

	}
	public String managerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		return "forward:/jsp/systemUserManagerPage.jsp";	
	}
	public String manager(HttpServletRequest request, HttpServletResponse response) throws IOException {
		return "forward:/jsp/auth/systemUser/systemUserPage.jsp";
	}
	@RequestMapping(value="/systemUser/t2")
	public void t1(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("managercc-t1");
		//return "";
	}
	@RequestMapping(value="/systemUser/t1")
	public void t2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("managercc-t2");
		//return "";
	}
	@RequestMapping(value="/t31")
	public void t3(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("managercc-t3");
		//return "";
	}
	
	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/systemUser/list")
	public void list(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		// systemUserQuery.setPageSize(20);
		//@SuppressWarnings("unused")
		// int x = systemUserQuery.getPageSize();
		System.out.println(systemUserQuery.getSort()+"--"+systemUserQuery.getDir()+"--"+systemUserQuery.getOrder());
		Page page = systemUserService.findPage(systemUserQuery);

		List<SystemUser> SystemUserlist = (List) page.getResult();
		ListRange<SystemUser> resultList = new ListRange<SystemUser>();
		resultList.setRows(SystemUserlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}
	public void jsonlist(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		// systemUserQuery.setPageSize(20);
		
		// int x = systemUserQuery.getPageSize();
		//if (true) throw new RuntimeException("eer");
//		if (true) throw java.lang.RuntimeException("");
//		Object a=new java.lang.RuntimeException("");
		
		Page page = systemUserService.findPage(systemUserQuery);

		List<SystemUser> SystemUserlist = (List) page.getResult();
		com.hh.bss.util.jquery.ListRange<SystemUser> resultList = new com.hh.bss.util.jquery.ListRange<SystemUser>();
		resultList.setRows(SystemUserlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void aaa(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("aaa:");
	}
	public void userlist(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		List l = SystemUserCache.getUserList(request.getParameter("q"));
		JsonConfig jsonConfig = new JsonConfig();
		Map mf = new HashMap();
		mf.put(SystemUser.class, new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				// name--map里key的字符，或是bean里的属性
				// map里的value,或是bean里的属性的值
				// 如果上层的数据给拦截了，那底层的数据将不能被转换
				// source 可能是hash或bean等
				Set set = new HashSet();
				set.add("id");
				set.add("account");
				set.add("name");
				if (SystemUser.class.equals(source.getClass()) && !set.contains(name)) {
					return true;
				}
				return false;
			}
		});
		jsonConfig.setJsonPropertyFilter(new MappingPropertyFilter(mf) {
			protected boolean keyMatches(Object key, Object source, String name, Object value) {
				return true;
			}
		});
		JsonHelper.outJsonString(response, JSONArray.fromObject(l, jsonConfig).toString());

	}

	public void listdata(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		// List l=SystemUserCache.getUserList();

		Map m = SystemUserCache.getSystemUserUsernameMap();
		JsonConfig jsonConfig = new JsonConfig();
		Map mf = new HashMap();
		mf.put(SystemUser.class, new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				// name--map里key的字符，或是bean里的属性
				// map里的value,或是bean里的属性的值
				// 如果上层的数据给拦截了，那底层的数据将不能被转换
				// source 可能是hash或bean等
				Set set = new HashSet();
				set.add("id");
				set.add("account");
				set.add("name");
				if (SystemUser.class.equals(source.getClass()) && !set.contains(name)) {
					return true;
				}
				return false;
			}
		});
		jsonConfig.setJsonPropertyFilter(new MappingPropertyFilter(mf) {
			protected boolean keyMatches(Object key, Object source, String name, Object value) {
				return true;
			}
		});
		StringBuffer sb = new StringBuffer();
		String jsonStr = null;
		if (m != null && m.size() > 0) {
			jsonStr = JSONObject.fromObject(m, jsonConfig).toString();
		}
		sb.append("var allUser=").append(jsonStr).append(";");

		JsonHelper.outJsonString(response, sb.toString());

	}

	public void userrolelist(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		List titlelist = (List) systemUserService.findUserRole(systemUserQuery);
		outJsonArray(response, titlelist);

	}
	public ModelAndView userrole(HttpServletRequest request, HttpServletResponse response, SystemUserQuery systemUserQuery) throws IOException {
		List titlelist = (List) systemUserService.findUserRole(systemUserQuery);
		ModelAndView mv = new ModelAndView();
		mv.addObject("userrole", titlelist);
		System.out.println("titlelist:"+titlelist);
		//mv.
		mv.setViewName("forward:/jsp/auth/systemUser/userRole.jsp");
		//res.setCharacterEncoding("UTF-8");
		
		return mv;
		//return "forward:/jsp/auth/systemUser/userRole.jsp";
	}	

	/**
	 * extGrid保存
	 * 
	 * @throws IOException
	 */
	public void save(HttpServletRequest request, HttpServletResponse response, SystemUser systemUser) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String passwd = request.getParameter("passwd");
			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(systemUser, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "createDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(systemUser, "createDt", new Date());
				} catch (Exception ex) {
				}
			}
			if (!StringHelper.isEmpty(passwd))
				systemUser.setPasswd(MD5Helper.encode(passwd));

			// 检查是否有重复用户
			SystemUser oldsystemUser = (SystemUser) systemUserService.findByUsername(systemUser.getAccount());
			if (oldsystemUser != null) {
				result.put("success", false);
				result.put("msg", "添加失败" + systemUser.getAccount() + "已经存在!");
				outJson(response, result);
				return;
			}
			systemUserService.save(systemUser);
			// 刷新用户缓存
			SystemUserCache.refresh();

			result.put("success", true);
			result.put("msg", "添加成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void modifypassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String username = request.getParameter("username");
			SystemUser oldsystemUser = (SystemUser) systemUserService.findByUsername(username);

			if (oldsystemUser == null) {
				result.put("success", false);
				result.put("msg", "修改失败,用户不存在!");
				outJson(response, result);
				return;
			}

			String newpasswd = request.getParameter("newpassword");
			String oldpasswd = request.getParameter("oldpassword");

			if (!oldsystemUser.getPasswd().equals(MD5Helper.encode(oldpasswd + Environment.PASSWORD_MD5_KEY))) {
				result.put("success", false);
				result.put("msg", "修改失败,旧密码不对!");
				outJson(response, result);
				return;
			}

			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			oldsystemUser.setPasswd(MD5Helper.encode(newpasswd + Environment.PASSWORD_MD5_KEY));

			//systemUserService.getEntityDao().getHibernateTemplate().update(oldsystemUser);
			//systemUserService.getEntityDao().getHibernateTemplate().
			systemUserService.updateUser(oldsystemUser);
			SystemUserCache.refresh();
			onlineManager.signOut();
			//response.sendRedirect("/login.html");
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response, SystemUser systemUser) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			SystemUser oldsystemUser = (SystemUser) systemUserService.getById(systemUser.getId());

			String passwd = request.getParameter("passwd");
			String emailPasswd = request.getParameter("emailPasswd");
			String oldPasswd = oldsystemUser.getPasswd();
			String oldEmailPasswd = oldsystemUser.getEmailPasswd();
			bind(request, oldsystemUser);
			oldsystemUser.setPasswd(oldPasswd);
			oldsystemUser.setEmailPasswd(oldEmailPasswd);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			if (!StringHelper.isEmpty(passwd))
				oldsystemUser.setPasswd(MD5Helper.encode(passwd + Environment.PASSWORD_MD5_KEY));
			if (!StringHelper.isEmpty(emailPasswd)) {
				// 加密
				String encryptStr = null;
				try {
					encryptStr = DESHelper.byte2hex(DESHelper.desEncrypt(emailPasswd.getBytes(), Environment.SECURE_KEY));
				} catch (Exception e) {
					e.printStackTrace();
				}
				oldsystemUser.setEmailPasswd(encryptStr);
				// oldsystemUser.setEmailPasswd(emailPasswd);
			}
			systemUserService.update(oldsystemUser);
			// 刷新用户缓存
			//SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void updateuser(HttpServletRequest request, HttpServletResponse response, SystemUser systemUser) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			SystemUser oldsystemUser = (SystemUser) systemUserService.getById(systemUser.getId());

			String passwd = request.getParameter("passwd");
			String emailPasswd = request.getParameter("emailPasswd");
			String oldPasswd = oldsystemUser.getPasswd();
			String oldEmailPasswd = oldsystemUser.getEmailPasswd();
			bind(request, oldsystemUser);
			oldsystemUser.setPasswd(oldPasswd);
			oldsystemUser.setEmailPasswd(oldEmailPasswd);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldsystemUser, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			if (!StringHelper.isEmpty(passwd))
				oldsystemUser.setPasswd(MD5Helper.encode(passwd));
			if (!StringHelper.isEmpty(emailPasswd)) {
				// 加密
				String encryptStr = null;
				try {
					encryptStr = DESHelper.byte2hex(DESHelper.desEncrypt(emailPasswd.getBytes(), Environment.SECURE_KEY));
				} catch (Exception e) {
					e.printStackTrace();
				}
				oldsystemUser.setEmailPasswd(encryptStr);
				// oldsystemUser.setEmailPasswd(emailPasswd);
			}
			systemUserService.updateUser(oldsystemUser);
			// 刷新用户缓存
			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid 批量修改
	 * 
	 * @throws IOException
	 */
	public void batchupdate(HttpServletRequest request, HttpServletResponse response, SystemUser systemUser) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String ids = request.getParameter("ids");

			// SystemUser oldsystemUser = (SystemUser)
			// systemUserService.getById(systemUser.getId());

			// bind(request, oldsystemUser);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(systemUser, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemUser.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(systemUser, "modifiedDt", new Date());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			if (StringUtils.isNotEmpty(ids)) {
				String[] idArr = ids.split(",");
				for (String id : idArr) {
					SystemUser oldsystemUser = (SystemUser) systemUserService.getById(Integer.valueOf(id));
					// if(systemUser.getBranchCompanyId() !=null &&
					// systemUser.getDeptId() != null && systemUser.getTitleId()
					// != null ){
					if (systemUser.getTitleIdString() != null) {
						// oldsystemUser.setBranchCompanyId(systemUser.getBranchCompanyId());
						// oldsystemUser.setDeptId(systemUser.getDeptId());
						oldsystemUser.setTitleIdString(systemUser.getTitleIdString());
						oldsystemUser.setModifier(systemUser.getModifier());
						oldsystemUser.setModifiedDt(systemUser.getModifiedDt());
					}
					if (StringUtils.isNotEmpty(systemUser.getStatus())) {
						oldsystemUser.setStatus(systemUser.getStatus());
						oldsystemUser.setModifier(systemUser.getModifier());
						oldsystemUser.setModifiedDt(systemUser.getModifiedDt());
					}
					systemUserService.update(oldsystemUser);
				}
			}
			// systemUserService.update(oldsystemUser);
			// 刷新用户缓存
			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid删除
	 * 
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			for (int i = 0; i < idarray.length; i++) {
				// 内置系统管理admin不能删除

				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);

				SystemUser user = SystemUserCache.getSystemUserById(id);
				if (user != null && "admin".equals(user.getAccount())) {
					throw new SystemException("内置用户不能删除");
				}
				systemUserService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void userrolesave(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// String ids = request.getParameter("ids");
		String[] ids = request.getParameterValues("id");
		String userId = request.getParameter("userId");
		String[] roleIds = request.getParameterValues("roleId");
		String[] hasRoles = request.getParameterValues("hasRole");

		SystemUserRoles systemUserRoles = null;
		Integer uId = StringHelper.parseInteger(userId, 0);
		List roles = new ArrayList();
		for (int i = 0; roleIds != null && i < roleIds.length; i++) {

			// if
			// (!(hasRoles!=null&&hasRoles.length>i&&hasRoles[i].equals("1"))){
			// continue;
			// }
			systemUserRoles = new SystemUserRoles();
			systemUserRoles.setRoleId(StringHelper.parseInteger(roleIds[i], 0));
			systemUserRoles.setUserId(uId);
			roles.add(systemUserRoles);

		}

		Map<String, Object> result = new HashMap<String, Object>();

		try {
			systemUserService.userRoleSave(uId, roles);
			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "修改成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}

		outJson(response, result);

	}

	public void setstafftitle(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String userId = request.getParameter("userId");
		String companyId = request.getParameter("companyId");
		String deptId = request.getParameter("deptId");
		String titleId = request.getParameter("titleId");

		Map<String, Object> result = new HashMap<String, Object>();

		try {
			SystemUser oldsystemUser = (SystemUser) systemUserService.getById(StringHelper.parseInteger(userId, 0));
			if (oldsystemUser != null) {
				oldsystemUser.setBranchCompanyId(StringHelper.parseInteger(companyId, 0));
				oldsystemUser.setDeptId(deptId);
				oldsystemUser.setTitleId(StringHelper.parseInteger(titleId, 0));
				systemUserService.update(oldsystemUser);
			}
			// systemUserService.userRoleSave(uId, roles);
			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "修改成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}

		outJson(response, result);

	}

	public void addstafftitle(HttpServletRequest request, HttpServletResponse response) throws IOException {

		Integer userId = StringHelper.parseInteger(request.getParameter("userId"), 0);
		String companyId = request.getParameter("companyId");
		Integer deptId = StringHelper.parseInteger(request.getParameter("deptId"), 0);
		Integer titleId = StringHelper.parseInteger(request.getParameter("titleId"), 0);

		Map<String, Object> result = new HashMap<String, Object>();

		try {
			if (userId.intValue() == 0 || titleId.intValue() == 0)
				throw new SystemException("参数错误");
			List values = new ArrayList();
			values.add(userId);
			values.add(titleId);
			List l = systemUserService.getEntityDao().getHibernateTemplate().find("from SystemUserTitle t where t.userId=? and t.titleId=?", values.toArray());
			if (l != null && l.size() > 0) {
				throw new SystemException("用户已存在相同的岗位");
			}
			SystemUserTitle systemUserTitle = new SystemUserTitle();
			systemUserTitle.setUserId(userId);
			systemUserTitle.setDeptId(deptId);
			systemUserTitle.setTitleId(titleId);
			systemUserTitle.setCreateDt(new Date());

			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				systemUserTitle.setCreator(onlineUser.getUsername());
			}

			systemUserService.getEntityDao().getHibernateTemplate().save(systemUserTitle);
			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "添加成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}

		outJson(response, result);

	}

	public void deletestafftitle(HttpServletRequest request, HttpServletResponse response) throws IOException {

		Integer userId = StringHelper.parseInteger(request.getParameter("userId"), 0);
		String companyId = request.getParameter("companyId");
		Integer deptId = StringHelper.parseInteger(request.getParameter("deptId"), 0);
		Integer titleId = StringHelper.parseInteger(request.getParameter("titleId"), 0);

		Map<String, Object> result = new HashMap<String, Object>();

		try {
			if (userId.intValue() == 0 || titleId.intValue() == 0)
				throw new SystemException("参数错误");
			List values = new ArrayList();
			values.add(userId);
			values.add(titleId);
			systemUserService.getEntityDao().getJdbcDao().update("delete from system_user_title  where user_id=? and title_id=?", values.toArray());

			SystemUserCache.refresh();
			result.put("success", true);
			result.put("msg", "删除成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}

		outJson(response, result);

	}

}
